﻿using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ControlsLibrary;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DbEntity.Client;

namespace TAProject.UI.Order
{
    public partial class FormClient : FormTemplate
    {
        private readonly IConnectionManager _connectionManager;
        private readonly IDataManager _dataManager;
        private readonly AEntityClient _aEntityClient;
        private readonly Form _parentForm;

        private DataTable _dataTableClient;

        public FormClient()
        {
            InitializeComponent();
        }

        public FormClient(Form parentForm, IDataManager dataManager, IConnectionManager connectionManager,
                          AEntityClient aEntityClient)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _connectionManager = connectionManager;
            _dataManager = dataManager;
            _aEntityClient = aEntityClient;

            _parentForm.Enabled = false;
            UpdateDataGridClient();
        }

        private void ButtonAddClick(object sender, EventArgs e)
        {
            if (CheckFields())
            {
                _aEntityClient.Surname = textBoxSurname.Text;
                _aEntityClient.Name = textBoxName.Text;
                _aEntityClient.FatherName = textBoxFatherName.Text;
                _aEntityClient.Telephone1 = controlTelephone1.Telephone;
                _aEntityClient.Telephone2 = controlTelephone2.Telephone;
                _aEntityClient.Adress = textBoxAdress.Text;
                _aEntityClient.Email = textBoxEmail.Text;
                _aEntityClient.AdditionatData = textBoxAdditionalData.Text;

                _aEntityClient.BlackList = false;

                string str;
                int rowAffected;

                if (buttonAdd.Text == "Добавить")
                {
                    rowAffected = _dataManager.ManageDataInDb(_aEntityClient.GetInsertQuery(),
                                                              _connectionManager.GetConnection());
                    str = _aEntityClient.GetInsertQuery();
                }
                else
                {
                    rowAffected = _dataManager.ManageDataInDb(_aEntityClient.GetUpdateQuery(),
                                                              _connectionManager.GetConnection());
                    str = _aEntityClient.GetUpdateQuery();
                }

                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка выполнения запроса. \n" + str);
                }
                else
                {
                    buttonAdd.Text = "Добавить";
                    UpdateDataGridClient();
                }
                buttonDelete.Enabled = true;
                buttonAddToBlackList.Enabled = true;
                ClearData();
            }
        }

        private void ButtonSelectClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityClient.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Hide_ID"].Value;
                _aEntityClient.Surname = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Фамилия"].Value.ToString();
                _aEntityClient.Name = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Имя"].Value.ToString();
                _aEntityClient.FatherName = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Отчество"].Value.ToString();
                _aEntityClient.Adress = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Адрес"].Value.ToString();
                FormClose();
            }
        }

        private void ButtonAddToBlackListClick(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Перенести этого клиента в черный список?", "", MessageBoxButtons.YesNo);
            if (dataGridView.CurrentRow != null && result == DialogResult.Yes)
            {
                _aEntityClient.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Hide_ID"].Value;
                var rowAffected = _dataManager.ManageDataInDb(EntityClientBlackList.MoveToBlackList(_aEntityClient.ID),
                                                              _connectionManager.GetConnection());

                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка выполнения запроса.");
                }
                else
                {
                    UpdateDataGridClient();
                }
            }
        }

        private void ButtonDeleteFromBlackListClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityClient.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Hide_ID"].Value;
                var rowAffected = _dataManager.ManageDataInDb(EntityClientBlackList.RemoveFromBlackList(_aEntityClient.ID),
                                                              _connectionManager.GetConnection());

                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка выполнения запроса.");
                }
                else
                {
                    UpdateDataGridClient();
                }
            }
        }

        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityClient.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Hide_ID"].Value;
                var rowAffected = _dataManager.ManageDataInDb(_aEntityClient.GetDeleteQuery(),
                                                              _connectionManager.GetConnection());

                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка выполнения запроса.");
                }
                else
                {
                    UpdateDataGridClient();
                }
            }
            ClearData();
        }

        private void ButtonCloseClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClient_Activated(object sender, EventArgs e)
        {
            CustomFillDataGridClient(_dataTableClient);
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        private bool CheckFields()
        {
            if (string.IsNullOrEmpty(textBoxSurname.Text) ||
                string.IsNullOrEmpty(textBoxName.Text) ||
                string.IsNullOrEmpty(textBoxFatherName.Text) ||
                string.IsNullOrEmpty(textBoxAdress.Text))
            {
                MessageBox.Show("Не все поля заполнены!");
                return false;
            }
            return true;
        }

        private void ClearData()
        {
            textBoxSurname.Text = string.Empty;
            textBoxName.Text = string.Empty;
            textBoxFatherName.Text = string.Empty;
            controlTelephone1.Telephone = string.Empty;
            controlTelephone2.Telephone = string.Empty;
            textBoxAdress.Text = string.Empty;
            textBoxEmail.Text = string.Empty;
            textBoxAdditionalData.Text = string.Empty;

            _aEntityClient.Name = string.Empty;
            _aEntityClient.Surname = string.Empty;
            _aEntityClient.FatherName = string.Empty;
            _aEntityClient.Adress = string.Empty;
            _aEntityClient.AdditionatData = string.Empty;
            _aEntityClient.Email = string.Empty;
            _aEntityClient.Telephone1 = string.Empty;
            _aEntityClient.Telephone2 = string.Empty;
        }

        private void ButtonEditClick(object sender, EventArgs e)
        {
            if(dataGridView.CurrentRow != null)
            {
                var telephone1 = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Тел 1"].Value.ToString().ToSimpleTelephone();
                var telephone2 = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Тел 2"].Value.ToString().ToSimpleTelephone();

                _aEntityClient.ID = (int)dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Hide_ID"].Value;
                textBoxSurname.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Фамилия"].Value.ToString();
                textBoxName.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Имя"].Value.ToString();
                textBoxFatherName.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Отчество"].Value.ToString();
                textBoxAdress.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Адрес"].Value.ToString();

                controlTelephone1.TelephoneMask = telephone1.Length < 7 && !string.IsNullOrEmpty(telephone1)
                        ? ControlTelephone.TelephoneType.City
                        : ControlTelephone.TelephoneType.Mobile;

                controlTelephone2.TelephoneMask = telephone2.Length < 7 && !string.IsNullOrEmpty(telephone2)
                        ? ControlTelephone.TelephoneType.City
                        : ControlTelephone.TelephoneType.Mobile;

                controlTelephone1.Telephone = telephone1;
                controlTelephone2.Telephone = telephone2;

                textBoxEmail.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Email"].Value.ToString();
                textBoxAdditionalData.Text = dataGridView.Rows[dataGridView.CurrentRow.Index].Cells["Дополнительные данные"].Value.ToString();

                buttonAdd.Text = "Сохранить";
                buttonDelete.Enabled = false;
                buttonAddToBlackList.Enabled = false;
                textBoxSurname.Focus();
            }
        }

        #region Filters
        private void TextBoxFilterSurnameTextChanged(object sender, EventArgs e)
        {
            textBoxFilterTelephone.Text = string.Empty;
            FilterClientsListBySurname((Control) sender);
        }

        private void TextBoxFilterTelephoneTextChanged(object sender, EventArgs e)
        {
            textBoxFilterSurname.Text = string.Empty;
            FilterClientsByTelephone(((Control) sender).Text);
        }
        #endregion

        #region DataTable management
        private void UpdateDataGridClient()
        {
            if (_connectionManager.CheckConnection())
            {
                _dataTableClient = _dataManager.GetDataTable(_aEntityClient.GetSelectQuery(),
                                                           _connectionManager.GetConnection());
                if (_dataTableClient != null)
                {
                    FillDataGridClient();
                }
                else
                {
                    MessageBox.Show("Данные отсутствуют.");
                }
            }
            else
            {
                MessageBox.Show("Ошибка подключения к БД.");
            }
        }

        private void FillDataGridClient()
        {
            if (_dataTableClient.Rows.Count > 0)
            {
                textBoxFilterSurname.Enabled = true;
                textBoxFilterTelephone.Enabled = true;
            }
            else
            {
                textBoxFilterSurname.Enabled = false;
                textBoxFilterTelephone.Enabled = false;
                MessageBox.Show("Данные отсутствуют");
            }
            CustomFillDataGridClient(_dataTableClient);
        }

        private void CustomFillDataGridClient(DataTable dataTable)
        {
            if (dataTable != null)
            {
                dataGridView.DataSource = dataTable;
                for (var i = 0; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView.Columns[i].Name.StartsWith("Hide"))
                    {
                        dataGridView.Columns[i].Visible = false;
                    }
                }

                for (var row = 0; row < dataGridView.Rows.Count; row++)
                {
                    if ((bool)dataGridView.Rows[row].Cells["Hide_BlackList"].Value)
                    {
                        dataGridView.Rows[row].DefaultCellStyle.BackColor = Color.Pink;
                        dataGridView.Rows[row].DefaultCellStyle.SelectionBackColor = Color.PaleVioletRed;
                    }
                }
            }
            else
            {
                MessageBox.Show("Данные отсутствуют.");
            }
        }
#endregion

        #region textBoxSurname
        private void TextBoxSurnameTextChanged(object sender, EventArgs e)
        {
            FilterClientsListBySurname((Control) sender);
        }
        #endregion

        #region textBoxTelephones
        private void TextBoxTelephonesTextChanged(object sender, EventArgs e)
        {
            FilterClientsByTelephone(((ControlTelephone) sender).Telephone);
        }
        private void OnFocusInOrOut(object sender, EventArgs e)
        {
            CustomFillDataGridClient(_dataTableClient);
        }
        #endregion

        private void FilterClientsListBySurname(Control textBox)
        {
            var dataTableClientsFilteredBySurname = _dataTableClient.AsEnumerable().
                Where(row => row.Field<string>("Фамилия").ToLower().StartsWith(textBox.Text.ToLower()));
            if (dataTableClientsFilteredBySurname.Any())
                CustomFillDataGridClient(dataTableClientsFilteredBySurname.CopyToDataTable());
            else
                CustomFillDataGridClient(_dataTableClient.Clone());//заполняем таблицу пустыми строками
        }

        private void FilterClientsByTelephone(string telephone)
        {
            var dataTableClientsFilteredByTelephone = _dataTableClient.AsEnumerable().
                    Where(
                        row =>
                        row.Field<string>("Тел 1").ToSimpleTelephone().StartsWith(telephone.ToSimpleTelephone()) ||
                        row.Field<string>("Тел 2").ToSimpleTelephone().StartsWith(telephone.ToSimpleTelephone()));
            if (dataTableClientsFilteredByTelephone.Any())
                CustomFillDataGridClient(dataTableClientsFilteredByTelephone.CopyToDataTable());
            else
                CustomFillDataGridClient(_dataTableClient.Clone()); //заполняем таблицу пустыми строками
        }
    }
}